﻿using Newtonsoft.Json;
using System;
using AbpProjectTemplate.Utilities.Enums;

namespace AbpProjectTemplate.Utilities.Json
{
    public class DescEnumJsonConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            var nullableType = Nullable.GetUnderlyingType(objectType);
            Type t = nullableType == null
                ? objectType
                : nullableType;

            return t.IsEnum;
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.Value == null)
                return null;

            if (Enum.TryParse(objectType, reader.Value.ToString(), out var val))
                return val;
            throw new AppUserFriendlyException($"数据：{reader.Value}不能转换成：{objectType.Name}.");
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            if (value == null)
                writer.WriteNull();
            else
                writer.WriteValue(value.GetDesc());
        }
    }
}


